import {onMounted, onUnmounted, ref, unref} from "vue";
import type {Ref} from "vue"

export function useContextMenu(containerRef: Ref) {
    const showMenu = ref(false)
    const x = ref(0)
    const y = ref(0)

    function handleContextMenu(e) {
        e.preventDefault()
        e.stopPropagation()
        showMenu.value = true
        x.value = e.clientX
        y.value = e.clientY
    }

    function closeMenu() {
        showMenu.value = false
    }

    onMounted(() => {
        const div = unref(containerRef)
        div.addEventListener('contextmenu', handleContextMenu)
        window.addEventListener('click', closeMenu, true)
        window.addEventListener('contextmenu', closeMenu, true)
    })
    onUnmounted(() => {
        const div = unref(containerRef)
        if (div) div.removeEventListener('contextmenu', handleContextMenu)
        window.removeEventListener('click', closeMenu, true)
        window.removeEventListener('contextmenu', closeMenu, true)
    })


    return {
        x,
        y,
        showMenu,
    }
}
